import React from "react";
import { View, Button, Image, Text } from "@tarojs/components";
import { uploadFile } from "@/request/upload";
import { ShowLoading, HideLoading, VibrateShort, defaultAvatarUrl } from "@/utils"
import './index.scss'
import Taro from "@tarojs/taro";

const Avatar: React.FC<{
  url?: string,
  onChange?: (url: string) => void,
  editMode?: boolean,
  showDetail?: boolean,
  size?: string,
  className?: string
}> = ({ url, onChange, editMode, size, className, showDetail }) => {

  const chooseavatar = (e) => {
    const tempFilePath = e.detail.avatarUrl
    ShowLoading('上传中')
    uploadFile('/file/ossUpload', tempFilePath, { path: 'avatar/' }).then(res => {
      if (typeof onChange === 'function') {
        onChange(res.data.url || '')
      }
    }).finally(() => {
      HideLoading()
    })
  }

  const preview = () => {
    showDetail ?
      Taro.previewImage({
        urls: [url || defaultAvatarUrl],
        current: 0
      }) : null
  }
  return (
    <View className={`avatar-container ${className || ''}`}>
      {
        url ?
            <Image onClick={preview} className='avatar-img' mode="aspectFill" src={url} style={{ width: size || '114rpx', height: size || '114rpx' }}></Image>:
            <Text className='avatar-img iconfont icon-yonghu' style={{fontSize: size || '114rpx'}}></Text>
      }
      {editMode ? <View className="edit-container">
        <View className="flex1"></View>
        <View className="replace font-size20 flex-row flex-center card-background">
          <Text className="iconfont">&#xe8c7;</Text>
          <Text className="text">更换</Text>
        </View>
        <Button onClick={() => VibrateShort()} className='wx-avatar-btn' open-type='chooseAvatar' onChooseAvatar={chooseavatar}>获取头像</Button>
      </View> : null}
    </View>
  )
}

export default Avatar